package com.example.divesb.http.converter.json;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Properties;

public class PropertiesHttpMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {

    public  PropertiesHttpMessageConverter(){
        super(new MediaType("text","properties"));
    }

    @Override
    protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        HttpHeaders httpHeaders = outputMessage.getHeaders();
        MediaType mediaType = httpHeaders.getContentType();
        //获取字符编码
        Charset charset =mediaType.getCharset();
        //不存在 默认UTF-8
        charset= charset == null ? Charset.forName("UTF-8") : charset;
        //properties -> string
        OutputStream outputStream = outputMessage.getBody();
        Writer writer = new OutputStreamWriter(outputStream,charset);
        properties.store(writer,"PropertiesHttpMessageConverter");


    }

    @Override
    protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {


        //从请求头content-type 解析编码
        HttpHeaders httpHeaders =inputMessage.getHeaders();
        MediaType mediaType = httpHeaders.getContentType();
        //获取字符编码
        Charset charset =mediaType.getCharset();
        //不存在 默认UTF-8
        charset= charset == null ? Charset.forName("UTF-8") : charset;
        Properties properties = new Properties();
        //字节流
        InputStream inputStream = inputMessage.getBody();
        //字符流 -> 字符编码
        InputStreamReader reader =new InputStreamReader(inputStream,charset);
        //加载字符流
        properties.load(reader);
        return properties;
    }

    @Override
    public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return readInternal(null,inputMessage);
    }
}
